<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        img{
            width: 100%;
        }
        .box{
            width: 300px;
            height: 300px;

            position: relative;
        }
        .max{
            display: none;
            width: 500px;
            height: 500px;
            position: absolute;
            left: 400px;
            top: 0;
            overflow: hidden;
            img{
                transform: scale(1.5);
                position: absolute;
                left: 100px;
                top: 100px;
            }
        }
        .mask{
            width: 200px;
            height: 200px;
            background-color: #2196f375;
            position: absolute;
           
            display: none;
        }
        
    </style>
</head>
<body>
    
    <div class="box">
        <img src="https://img14.360buyimg.com/n1/s450x450_jfs/t1/280670/35/28774/100891/6819a12eFe6c70ca5/91fd222631587cac.jpg.avif" alt="">
        <div class="mask"></div>
    </div>
    <div class="max">
        <img class="max-img" src="https://img14.360buyimg.com/n1/s450x450_jfs/t1/280670/35/28774/100891/6819a12eFe6c70ca5/91fd222631587cac.jpg.avif" alt="">
    </div>
    <script>
        let box = document.querySelector('.box')
        let max = document.querySelector('.max')
        let mask = document.querySelector('.mask')
        let img = document.querySelector('.max-img')
        // 鼠标移入
        box.addEventListener('mouseover',function(){
            // 1.显示选中区域
            mask.style.display = 'block'
            // 2.显示大图
            max.style.display = 'block'
        })
        
        // 鼠标移出
        box.addEventListener('mouseout',function(){
            // 1.显示选中区域
            mask.style.display = 'none'
            // 2.显示大图
            max.style.display = 'none'
        })

        box.addEventListener('mousemove',function(e){
            let top = e.pageY -mask.offsetHeight/2
            let left = e.pageX-mask.offsetWidth/2
           
            let maxtop = box.offsetWidth-mask.offsetWidth
            let maxleft = box.offsetHeight-mask.offsetHeight

            // 限制移动范围
            top = top<0?0:top
           top = top>maxtop?maxtop:top
           left = left<0?0:left
           left = left>maxleft?maxleft:left
            
            // 放大镜的位置
            mask.style.top = top+'px'
            mask.style.left = left+'px'
            // 大图的位置
            img.style.top = -3*top+'px'
             img.style.left = -3*left+'px'
        })
        
    </script>
</body>
</html>